/* $Id: stamp.c 57 2007-03-25 09:14:34Z aldleonm $
 */
#include "encdb.h"
#include "extern.h"
#include "db.h"

extern struct _dbi *db_i;
extern struct _dbid *db_id;

int
setID(void)
{

	if (db_i->action == CREATE) {

		strncpy(db_id->name, db_i->name, strlen(db_i->name));
		db_id->creation_date = time(0);
		db_id->last_change = time(0);
		db_id->item_counter = db_i->item_counter;

		if ((WriteDB(db_i->pdb, ID_KEY, db_id, sizeof(struct _dbid)))) {
			fprintf(stderr, "Error writting id to database...\n");
			return (EXIT_FAILURE);
		}

		return (EXIT_SUCCESS);

	} else {

		u_int32_t rsz;

		if (!(db_id = (struct _dbid *) QueryDB(db_i->pdb, ID_KEY, &rsz))) {
			fprintf(stderr, "Error getting database id...\n");
			if (debug == 1)
				fprintf(stderr, "setID(): read %u from %s.\n", rsz, ID_KEY);
			return (EXIT_FAILURE);
		}

		if (strncmp(db_i->name, db_id->name, strlen(db_i->name))) {
			fprintf(stderr,
							"The database name given does not match the database name found...\n");
			return (EXIT_FAILURE);
		}

		db_id->last_change = time(0);
		db_id->item_counter = db_i->item_counter;

		if ((DeleteDB(db_i->pdb, ID_KEY))) {
			fprintf(stderr, "Error deleting database id...\n");
			return (EXIT_FAILURE);
		}

		if ((WriteDB(db_i->pdb, ID_KEY, db_id, sizeof(struct _dbid)))) {
			fprintf(stderr, "Error writting id to database...\n");
			return (EXIT_FAILURE);
		}

		return (EXIT_SUCCESS);
	}

	/* NOT REACHED */

}

int
getID(void)
{
	if (db_i->action == 0) {

		fprintf(stderr, "This is a new database!, there is no id in it.\n");
		return (EXIT_FAILURE);

	} else {

		u_int32_t rsz;

		if (!(db_id = (struct _dbid *) QueryDB(db_i->pdb, ID_KEY, &rsz))) {
			fprintf(stderr, "Error getting database id...\n");
			if (debug == 1)
				fprintf(stderr, "getID(): read %u from %s.\n", rsz, ID_KEY);
			return (EXIT_FAILURE);
		}
		return (EXIT_SUCCESS);
	}
	/* NOT REACHED */
}
/*
 * vim:ts=2
 */
/* END */
